package com.xingdata.jjxc.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;

import com.xingdata.jjxc.R;

/**
 * @描述 TODO(图片下载工具类)
 * @类名称 ImageTools.java
 * @包名 com.newtouch.crm1_2.entity
 * @创建时间 2014-8-11 上午11:14:38
 * @创建人 JiangMin
 * @版本号 V1.0
 */
public class ImageTools {
	private static boolean LocalImagesucceed = true;
	private static String TAG = "ImageTools";

	/**
	 * 根据URI获取网络图片
	 * 
	 * @param mContext
	 * 
	 * @param bitmapMap
	 * 
	 * @param url
	 * @param isSave
	 *            是否保存图片
	 * @return Bitmap
	 */
	public static Bitmap getUrlImage(Context mContext, String url,
			boolean isSave ,Float fMulriple) {
		// 这里先判断SD卡是否有保存图片
		Bitmap bmp = SDCardTools.getSDImage(url,fMulriple);
		if (bmp == null && url != null && url.length() != 0) {
			if (NetworkTools.isNetAvailable(mContext)) {
				URL mUrl = null;
				InputStream inputStream = null;
				HttpURLConnection urlConnection = null;
				try {
					mUrl = new URL(url);
					urlConnection = (HttpURLConnection) mUrl.openConnection();
					urlConnection.setRequestMethod("GET");
					// 超时时间
					urlConnection.setConnectTimeout(10000);
					// 设置HttpURLConnection请求头里面的属性
					urlConnection.setRequestProperty("Content-type",
							"application/x-www-form-urlencoded");
					if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
						inputStream = urlConnection.getInputStream();
						byte[] bt = getBytesFromStream(inputStream);
						Bitmap bitmap = BitmapFactory.decodeByteArray(bt, 0,
								bt.length);
						bmp = bitmap;
						if (bmp != null) {
							LocalImagesucceed = true;
						} else {
							LocalImagesucceed = false;
						}
					} else {
						LocalImagesucceed = false;
						Log.e("ImageTools", url + "  IS     ERROR!");
					}
				} catch (MalformedURLException e) {
					LocalImagesucceed = false;
					Log.e(TAG, "URL  is  error!");
				} catch (IOException e) {
					SDCardTools.deleteImage(changeImageName(url));
					LocalImagesucceed = false;
					Log.e(TAG, url + "Loading is  Error!");
				} finally {
					if (null != inputStream) {
						try {
							inputStream.close();
							inputStream = null;
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (null != urlConnection) {
						urlConnection.disconnect();
						urlConnection = null;
					}
				}
				// 下载成功保存图片
				if (LocalImagesucceed ) {
					if (isObjNull(bmp)) {
						SDCardTools.SaveUrlImage(url, bmp);
						bmp.recycle();
						bmp=null;
						bmp=SDCardTools.getSDImage(url,fMulriple);
					}
				}
			} 
		}
		return bmp;

	}

//	/**
//	 * 根据URI和图片名获取网络图片
//	 * 
//	 * @param mContext
//	 * 
//	 * @param bitmapMap
//	 * 
//	 * @param url
//	 * @param isSave
//	 *            是否保存图片
//	 * @return Bitmap
//	 */
//	public static Bitmap getUrlImage(Context mContext, String url,
//			String imgName, boolean isSave,Float fMulriple) {
//		// 这里先判断SD卡是否有保存图片
//		Bitmap bmp = SDCardTools.getSDImage(imgName,fMulriple);
//		if (bmp == null && url != null && url.length() != 0) {
//			if (NetworkTools.isNetAvailable(mContext)) {
//				URL mUrl = null;
//				InputStream inputStream = null;
//				HttpURLConnection urlConnection = null;
//				try {
//					mUrl = new URL(url);
//					urlConnection = (HttpURLConnection) mUrl.openConnection();
//					urlConnection.setRequestMethod("GET");
//					// 超时时间
//					urlConnection.setConnectTimeout(10000);
//					// 设置HttpURLConnection请求头里面的属性
//					urlConnection.setRequestProperty("Content-type",
//							"application/x-www-form-urlencoded");
//					if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//						inputStream = urlConnection.getInputStream();
//						byte[] bt = getBytesFromStream(inputStream);
//						Bitmap bitmap = BitmapFactory.decodeByteArray(bt, 0,
//								bt.length);
//						bmp = bitmap;
//						if (bmp != null) {
//							LocalImagesucceed = true;
//						} else {
//							LocalImagesucceed = false;
//							bmp = newBitMap(mContext);
//						}
//					} else {
//						LocalImagesucceed = false;
//						Log.e("ImageTools", url + "  IS     ERROR!");
//						bmp = newBitMap(mContext);
//					}
//				} catch (MalformedURLException e) {
//					LocalImagesucceed = false;
//					Log.e(TAG, "URL  is  error!");
//					bmp = newBitMap(mContext);
//				} catch (IOException e) {
//					SDCardTools.deleteImage(changeImageName(imgName));
//					LocalImagesucceed = false;
//					Log.e(TAG, url + "Loading is  Error!");
//					bmp = newBitMap(mContext);
//				} finally {
//					if (null != inputStream) {
//						try {
//							inputStream.close();
//							inputStream = null;
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
//					}
//					if (null != urlConnection) {
//						urlConnection.disconnect();
//						urlConnection = null;
//					}
//				}
//				// 下载成功保存图片
//				if (LocalImagesucceed && isSave) {
//					if (isObjNull(bmp)) {
//						SDCardTools.SaveUrlImage(imgName, bmp);
//					}
//				}
//			} else {
//				bmp = newBitMap(mContext);
//			}
//		}
//
//		return bmp;
//
//	}

	/**
	 * 将数据流转换为byte
	 * 
	 * @param
	 * @return
	 */

	private static byte[] getBytesFromStream(InputStream inputStream) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while (len != -1) {
			try {
				len = inputStream.read(b);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (len != -1) {
				baos.write(b, 0, len);
			}
		}

		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return baos.toByteArray();
	}

	/**
	 * 根据URL更改保存图片名称 格式必须为jpg或者png
	 * 
	 * @param url
	 * @return
	 */
	public static String changeImageName(String url) {

		String name = "";
		try {
			name = url.substring(url.lastIndexOf("/") + 1);
		} catch (Exception e) {
			name = null;
			e.printStackTrace();
		}
		return name;
	}

	/**
	 * 异常处理图片防止报空
	 * 
	 * @param mContext
	 * @return
	 */
	private static Bitmap newBitMap(Context mContext) {
		BitmapDrawable bd = (BitmapDrawable) mContext.getResources()
				.getDrawable(R.drawable.ic_launcher);
		return bd.getBitmap();
	}

	/**
	 * 对象是否为空 如果对象为null返回true
	 * 
	 * @return
	 */
	private static boolean isObjNull(Object object) {
		if (object == null) {
			return false;
		}
		return true;
	}

	/**
	 * 根据目录获取本地压缩图片
	 * 
	 * @param srcPath
	 * @param fMulriple
	 * @return
	 */
	public static Bitmap compressImageFromFile(String srcPath, Float fMulriple) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		newOpts.inJustDecodeBounds = true;// 只读边,不读内容
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		if (new File(srcPath)==null) {
			return null;
		}
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = ViewTools.getScreenHight() / fMulriple;// 实际屏幕高度
		float ww = ViewTools.getScreenWidth() / fMulriple;// 实际屏幕宽度
		int be = 1;
		if (w > h && w > ww) {
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置采样率
		newOpts.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设
		newOpts.inPurgeable = true;// 同时设置才会有效
		newOpts.inInputShareable = true;// 。当系统内存不够时候图片自动被回收

		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
		// 其实是无效的,大家尽管尝试
		return bitmap;
	}

}
